<?php
namespace Admin\Model;
use Think\Model;
/**
 * 栏目分类模型model
 */
 class ModelModel extends Model{
 	
	 //定义空自动验证
	 public $_validate = array();
 	/**
	 * 添加模型方法
	 */
	 public function addContentModel(){
	 	$this->_validate = array(
			array('mname','require','模型名称不能为空'),
			array('mmodel_name','require','模型表名不能为空'),
			array('mfield','require','模型标示名不能为空'),
			array('mtype','require','模型性质不能为空'),
//			array('mpost','require','发布程序不能为空'),
//			array('medit','require','修改程序不能为空'),
//			array('madmin','require','管理程序不能为空'),	
			array('mmodel_name', "/^[".chr(0xa1)."-".chr(0xff)."A-Za-z0-9_]+$/" , '模型表名格式有误,请使用英文字母组合格式' , 1 , 'regex' ,1),
			array('mfield', "/^[".chr(0xa1)."-".chr(0xff)."A-Za-z0-9_]+$/" , '模型标示名格式有误,请使用字母组合' , 1 , 'regex' ,1)
		);
		if(!$this->create()){
			return false;
		}
		//组合数据
		$mmodel_name = i('post.mmodel_name').'onmodel';
		$data = array(
			'mname'           =>  i('post.mname'),
			'mmodel_name'     =>  $mmodel_name  ,
			'mfield'     	  =>  i('post.mfield'),
			'mtype'   		  =>  i('post.mtype'),
			'mpost'    		  =>  i('post.mpost'),
			'medit'  		  =>  i('post.medit'),
			'madmin'  		  =>  i('post.madmin'),
			'mname'   		  =>  i('post.mname'),
			'mname'  		  =>  i('post.mname'),
			'mdefault_field'  =>  'defaultonmodel',
		);
		//新建模型表字段  建表并初始化 添加 id、 栏目id 、 内容字段
		$query = "DROP TABLE IF EXISTS `duosute`.`duosute_".$data['mmodel_name']."`;CREATE TABLE IF NOT EXISTS `duosute`.`duosute_".$data['mmodel_name']."` (`id` INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '".$data['mname']."id',`cid` INT UNSIGNED NOT NULL DEFAULT 0,`aid` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '文章id',`content` TEXT NULL COMMENT '内容文本|textarea|',PRIMARY KEY (`id`),UNIQUE INDEX `iid_UNIQUE` (`id` ASC))ENGINE = MyISAM
COMMENT = '".$data['mname']."';";
echo $query;die;
			//执行创建表语句
		$comment =M()->execute($query);
		//写入数据库
		$databack = M('model')->add($data);
		//返回结果
		if($databack){
			return true;
		}else{
			$this->error='添加失败';
			return false;
		}
	 }
	
	
	
	
	/**
	 * 修改更新模型
	 * 
	 */
	 public function editContentModel($modelName){
	 	$this->_validate = array(
			array('mname','require','模型名称不能为空'),			
			array('mtype','require','模型性质不能为空'),
			array('mpost','require','发布程序不能为空'),
			array('medit','require','修改程序不能为空'),
			array('madmin','require','管理程序不能为空'),	
			
		);
		if(!$this->create()){
			return false;
		}
		//组合数据
		$mmodel_name = i('post.mmodel_name').'onmodel';
		$data = array(
			'mname'           =>  i('post.mname'),
			'mtype'   		  =>  i('post.mtype'),
			'mpost'    		  =>  i('post.mpost'),
			'medit'  		  =>  i('post.medit'),
			'madmin'  		  =>  i('post.madmin'),
			'mname'   		  =>  i('post.mname'),
			'mname'  		  =>  i('post.mname'),
			'mdefault_field'  =>  'defaultonmodel',
		);
		
		//写入数据库
		$databack = M('model')->where("mmodel_name ='{$modelName}'")->save($data);
		//返回结果
		if($databack){
			return true;
		}else{
			$this->error='无变更信息或更新失败';
			return false;
		}
	 }
	 
	 
	 
	 
	 /**
	  * 检查字段是否重复
	  */
	 protected function checkName(){
		//组合查询语句
		$showtable = "SHOW FULL FIELDS FROM duosute_".$this->mname;
		//执行语句查询数据
		$dataInfo = M()->query($showtable);
		//如果有返回结果
		if($dataInfo){
			//循环便利数据判断是否从在
			foreach($dataInfo as $k => $v){
				$bool = in_array($this->mmodel_name,$v);
				//找到就返回false提示重复
				if($bool){
					return false;
				}
			}			
		}
		return true;
	}

	 /**
	  * 添加字段
	  */
	  public function addField($mname){
	  	header("Content-type:text/html;charset=utf-8");
	  	$this->mname = $mname;
	  	$this->mmodel_name = i('post.mmodel_name');
	  	$this->_validate = array(
			array('comment','require','表单提示文字不能为空'),
			array('mmodel_name','require','字段名不能为空'),
			array('mtype',"/[a-zA-Z]/",'数据类型未选择或异常' , 1 , 'regex' ,1),
			array('inputType',"/[a-zA-Z]/",'表单类型不能为空' , 1 , 'regex' ,1),
			array('mmodel_name', "/^[".chr(0xa1)."-".chr(0xff)."A-Za-z0-9_]+$/" , '字段名格式有误,请使用英文字母组合格式' , 1 , 'regex' ,1),
			array('mmodel_name','checkName','字段名已经存在！',1,'callback'),
		);
		//组合数据
		$data = array(
			'comment'         =>  i('post.comment'),//表单提示文字
			'mmodel_name'     =>  i('post.mmodel_name'),//字段名称
			'mtype'     	  =>  i('post.mtype'),//数据类型
			'inputType'       =>  i('post.inputType'),//表单类型
			'mdefault'   	  =>  i('post.defaultValue'),//默认值
			'mlength'         =>  i('post.mlength'),//最大长度
		);
		//自动验证
		if(!$this->create()){
			return false;
		};
		//字段名不能未见关键
		if($data['mmodel_name'] == 'char' || $data['mmodel_name'] == 'option' || $data['mmodel_name'] == 'mediumtext' || $data['mmodel_name'] == 'text' || $data['mmodel_name'] =='tinyint' || $data['mmodel_name'] == 'smallint' || $data['mmodel_name'] == 'int' || $data['mmodel_name'] == 'enum' || $data['mmodel_name'] == 'set' || $data['mmodel_name'] == 'decimal' ){
			$this->error='字段名不能为关键字';
			return false;
		}
		//判断字段类型  赋值字段长度  //单行文本类型默认 255字符 默认值为空
		if($data['mtype'] == 'char'){
			//判断长度是否在有效范围之内
			if($data['mlength']<=0 || $data['mlength'] >255){
				$this->error="最大长度不在有效范围之内";
				return false;
			}
			$data['mlength']=$data['mlength']?(int)$data['mlength']:255;
			//定义字段类型
			$data['typeOption'] = $data['mtype']."(".$data['mlength'].")";
			$data['mdefault']=$data['mdefault']?$data['mdefault']:'';
			$query = "alter table   duosute_".$mname." add ". $data['mmodel_name'] .  " ". $data['mtype']."(".$data['mlength'].")  not Null default '".$data['mdefault']."' COMMENT '".$data['comment']."|".$data['inputType']."|".$data['mdefault']."'";
		}
		
		//长文本类型
		if($data['mtype'] == 'mediumtext' || $data['mtype'] == 'text'){
			$data['mlength']='';
			$data['mdefault']=$data['mdefault']?$data['mdefault']:'';
			$data['typeOption'] = $data['mtype'];
			$query = "alter table   duosute_".$mname." add ". $data['mmodel_name'] .  " ". $data['mtype']." not Null default '' COMMENT '".$data['comment']."|".$data['inputType']."|".$data['mdefault']."'";
		}
		
		//数字类型判断
		if($data['mtype'] == 'int' || $data['mtype'] == 'smallint' || $data['mtype'] == 'tinyint'){
			//tinyint小整形0-255
			if($data['mtype'] == 'tinyint'){
				if($data['mlength']<=0 || $data['mlength']>3){
					$this->error='tinyint类型长度范围在1-3位之间';
					return false;
				}
			}
			//int
			if($data['mtype'] == 'int'){
				if($data['mlength']<=0 || $data['mlength']>10){
					$this->error='int类型长度范围在1-10位之间';
					return false;
				}
			}
			//smallint
			if($data['mtype'] == 'smallint'){
				if($data['mlength']<=0 || $data['mlength']>5){
					$this->error='smallint类型长度范围在1-5位之间';
					return false;
				}
			}
			
			$data['mlength']=$data['mlength']?(int)$data['mlength']:3;
			$data['mdefault']=$data['mdefault']?(int)$data['mdefault']:'0';
			$data['typeOption'] = $data['mtype'];
			$query = "alter table duosute_".$mname." add ". $data['mmodel_name'] .  " ". $data['mtype']." unsigned not Null default '".$data['mdefault']."' COMMENT '".$data['comment']."|".$data['inputType']."|".$data['mdefault']."'";
		}
		
		//多选单选类型
		if($data['mtype'] == 'enum'  || $data['mtype'] == 'set'){
			$data['mlength']='';
			if($data['mdefault'] == ''){
				$this->error='单选和多选时务必输入选择项，至少两个选项项用，号隔开，第二个口号前内容设置默认选择值';
				return false;
			}else{
				//至少出现一次","号来判断是否有默认选择值 //默认过滤英文','号
				$data['mdefault'] = str_ireplace(array("'","‘","’","（","）","(",")","，",".","。","、"),"", $data['mdefault']);//默认统一过滤字符前后出现符号
				$data['mdefault'] = str_ireplace(",","，", $data['mdefault']);//全角半角转换
				$match = strpos($data['mdefault'], '，',1);
				if(!$match){
					$this->error='单选和多选时务必输入选择项，至少两个选项项用，号隔开，第二个口号前内容设置默认选择值';
					return false;
				}else{
					 $data['default'] = strchr($data['mdefault'], '，', true) ;
				}
			}
			//将默认值用于设置选项 截取第一个','号前内容做默认选项
			$data['mdefault'] = str_ireplace("，", "','", $data['mdefault']); 
			$data['typeOption'] = $data['mtype']."(".$data['mdefault'].")";
			$data['dvalue'] = str_ireplace("'",'',$data['mdefault']);//echo $data['dvalue'].'<hr />';
			//截取定义字段默认值			
			$query = "alter table   duosute_".$mname." add ". $data['mmodel_name'] .  " ".$data['mtype']."('".$data['mdefault']."') not Null default '".$data['default']."' COMMENT '".$data['comment']."|".$data['inputType']."|".$data['dvalue']."'";
			//echo $query;die;
		}
		if($data['mtype'] == 'decimal'){			
			$data['mlength']='';
			if($data['mdefault'] == ''){
				$data['mdefault'] = '6';
			}else{
				$data['mdefault'] = str_ireplace(array("'","‘","’","（","）","(",")","，",".","。","、"),"", $data['mdefault']);//默认统一过滤所有"'"号
				$data['mdefault'] = str_ireplace(",",",", $data['mdefault']);//全角半角转换	
				$data['default'] = strchr($data['mdefault'], ',', true) ;
				//取值范围提示
				if($data['default'] >65 || $data['default']<1){
					$this->error='请确认decimal范围在1-65位之间';
					return false;
				}				
			}
	  		$query = "alter table   duosute_".$mname." add ". $data['mmodel_name'].  " ". $data['mtype']."(".$data['mdefault'].")  not Null default '0.00'  COMMENT '".$data['comment']."|".$data['inputType']."|".$data['mdefault']."'";
	  	}
			//如果选择input类型为下拉框
			if($data['inputType']== 'option'){
				if($data['mtype'] == 'enum'  || $data['mtype'] == 'set'){
					$this->error='下拉框类型下不建议选择单选和多选字段';
					return false;
				}
				echo $data['mdefault'].'<hr />';
				//如果是数字类型 
				
				//如果是文本类型
				
				//如果是
				$data['mdefault'] = str_ireplace(array("'","‘","’","（","）","(",")","，",".","。","、"),",", $data['mdefault']);//默认统一过滤所有"'"号
				$query = "alter table   duosute_".$mname." add ". $data['mmodel_name'] .  " ".$data['typeOption']."  COMMENT '".$data['comment']."|".$data['inputType']."|".$data['mdefault']."'";
			}
			echo $query;
		//执行语句 建立字段
		$comment =M()->execute($query);
		return true;
	 }


	 /**
	  * 添加字段
	  */
	  
	  public function editField($mname,$field){
	  	header("Content-type:text/html;charset=utf-8");
	  	$this->mname = $mname;
	  	$this->mmodel_name = i('post.mmodel_name');
	  	$this->_validate = array(
			array('comment','require','表单提示文字不能为空'),
			array('mtype',"/[a-zA-Z]/",'数据类型未选择或异常' , 1 , 'regex' ,1),
			array('inputType',"/[a-zA-Z]/",'表单类型不能为空' , 1 , 'regex' ,1),
			
		);
		//组合数据
		$data = array(
			'comment'         =>  i('post.comment'),//表单提示文字
			'mtype'     	  =>  i('post.mtype'),//数据类型
			'inputType'       =>  i('post.inputType'),//表单类型
			'mdefault'   	  =>  i('post.defaultValue'),//默认值
			'mlength'         =>  i('post.mlength'),//最大长度
		);
		//自动验证
		if(!$this->create()){
			return false;
		};
		//判断字段类型  赋值字段长度  //单行文本类型默认 255字符 默认值为空
		if($data['mtype'] == 'char'){
			//判断长度是否在有效范围之内
			if($data['mlength']<=0 || $data['mlength'] >255){
				$this->error="最大长度不在有效范围之内";
				return false;
			}
			$data['mlength']=$data['mlength']?(int)$data['mlength']:255;
			//定义字段类型
			$data['typeOption'] = $data['mtype']."(".$data['mlength'].")";
			$data['mdefault']=$data['mdefault']?$data['mdefault']:'';
			$query = "alter table   duosute_".$mname." modify ". $field .  " ". $data['mtype']."(".$data['mlength'].")  not Null default '".$data['mdefault']."' COMMENT '".$data['comment']."|".$data['inputType']."|".$data['mdefault']."'";
		}
		
		//长文本类型
		if($data['mtype'] == 'mediumtext' || $data['mtype'] == 'text'){
			$data['mlength']='';
			$data['mdefault']=$data['mdefault']?$data['mdefault']:'';
			$data['typeOption'] = $data['mtype'];
			$query = "alter table   duosute_".$mname." modify ". $field .  " ". $data['mtype']." not Null default '' COMMENT '".$data['comment']."|".$data['inputType']."|".$data['mdefault']."'";
		}
		
		//数字类型判断
		if($data['mtype'] == 'int' || $data['mtype'] == 'smallint' || $data['mtype'] == 'tinyint'){
			//tinyint小整形0-255
			if($data['mtype'] == 'tinyint'){
				if($data['mlength']<=0 || $data['mlength']>3){
					$this->error='tinyint类型长度范围在1-3位之间';
					return false;
				}
			}
			//int
			if($data['mtype'] == 'int'){
				if($data['mlength']<=0 || $data['mlength']>10){
					$this->error='int类型长度范围在1-10位之间';
					return false;
				}
			}
			//smallint
			if($data['mtype'] == 'smallint'){
				if($data['mlength']<=0 || $data['mlength']>5){
					$this->error='smallint类型长度范围在1-5位之间';
					return false;
				}
			}
			
			$data['mlength']=$data['mlength']?(int)$data['mlength']:3;
			$data['mdefault']=$data['mdefault']?(int)$data['mdefault']:'0';
			$data['typeOption'] = $data['mtype'];
			$query = "alter table duosute_".$mname." modify ". $field .  " ". $data['mtype']." unsigned not Null default '".$data['mdefault']."' COMMENT '".$data['comment']."|".$data['inputType']."|".$data['mdefault']."'";
		}
		
		//多选单选类型
		if($data['mtype'] == 'enum'  || $data['mtype'] == 'set'){
			$data['mlength']='';
			if($data['mdefault'] == ''){
				$this->error='单选和多选时务必输入选择项，至少两个选项项用，号隔开，第二个口号前内容设置默认选择值';
				return false;
			}else{
				//至少出现一次","号来判断是否有默认选择值 //默认过滤英文','号
				$data['mdefault'] = str_ireplace(array("'","‘","’","（","）","(",")","，",".","。","、"),"", $data['mdefault']);//默认统一过滤字符前后出现符号
				$data['mdefault'] = str_ireplace(",","，", $data['mdefault']);//全角半角转换
				$match = strpos($data['mdefault'], '，',1);
				if(!$match){
					$this->error='单选和多选时务必输入选择项，至少两个选项项用，号隔开，第二个口号前内容设置默认选择值';
					return false;
				}else{
					 $data['default'] = strchr($data['mdefault'], '，', true) ;
				}
			}
			//将默认值用于设置选项 截取第一个','号前内容做默认选项
			$data['mdefault'] = str_ireplace("，", "','", $data['mdefault']); 
			$data['typeOption'] = $data['mtype']."(".$data['mdefault'].")";
			$data['dvalue'] = str_ireplace("'",'',$data['mdefault']);//echo $data['dvalue'].'<hr />';
			//截取定义字段默认值			
			$query = "alter table   duosute_".$mname." modify ". $field .  " ".$data['mtype']."('".$data['mdefault']."') not Null default '".$data['default']."' COMMENT '".$data['comment']."|".$data['inputType']."|".$data['dvalue']."'";
			//echo $query;die;
		}
		if($data['mtype'] == 'decimal'){			
			$data['mlength']='';
			if($data['mdefault'] == ''){
				$data['mdefault'] = '6';
			}else{
				$data['mdefault'] = str_ireplace(array("'","‘","’","（","）","(",")","，",".","。","、"),"", $data['mdefault']);//默认统一过滤所有"'"号
				$data['mdefault'] = str_ireplace(",",",", $data['mdefault']);//全角半角转换	
				$data['default'] = strchr($data['mdefault'], ',', true) ;
				//取值范围提示
				if($data['default'] >65 || $data['default']<1){
					$this->error='请确认decimal范围在1-65位之间';
					return false;
				}				
			}
	  		$query = "alter table   duosute_".$mname." modify ". $field.  " ". $data['mtype']."(".$data['mdefault'].")  not Null default '0.00'  COMMENT '".$data['comment']."|".$data['inputType']."|".$data['mdefault']."'";
	  	}
			//如果选择input类型为下拉框
			if($data['inputType']== 'option'){
				if($data['mtype'] == 'enum'  || $data['mtype'] == 'set'){
					$this->error='下拉框类型下不建议选择单选和多选字段';
					return false;
				}
				echo $data['mdefault'].'<hr />';
				//如果是数字类型 
				
				//如果是文本类型
				
				//如果是
				$data['mdefault'] = str_ireplace(array("'","‘","’","（","）","(",")","，",".","。","、"),",", $data['mdefault']);//默认统一过滤所有"'"号
				$query = "alter table   duosute_".$mname." modify ". $field .  " ".$data['typeOption']."  COMMENT '".$data['comment']."|".$data['inputType']."|".$data['mdefault']."'";
			}
			echo $query;
		//执行语句 建立字段
		$comment =M()->execute($query);
		return true;
	 }



	 
 }
